package com.wpml.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wpml.common.constant.ProductConstant;
import com.wpml.common.util.PageUtils;
import com.wpml.common.util.Query;
import com.wpml.common.util.RUtil;
import com.wpml.common.util.ResultJson;
import com.wpml.coupon.api.CouponFeignClient;
import com.wpml.coupon.to.SkuReductionTo;
import com.wpml.coupon.to.SpuBoundTo;
import com.wpml.product.dao.SpuInfoDao;
import com.wpml.product.entity.*;
import com.wpml.product.service.*;
import com.wpml.product.vo.*;
import com.wpml.search.api.SearchFeignClient;
import com.wpml.search.vo.SkuEsModel;
import com.wpml.ware.api.WareFeignClient;
import com.wpml.ware.vo.SkuHasStockVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * spu信息(PmsSpuInfo)表服务实现类
 *
 * @author makejava
 * @since 2020-04-07 11:33:37
 */
@Service
@Slf4j
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoModel> implements SpuInfoService {
    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService imagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService attrValueService;

    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    CouponFeignClient couponFeignService;
    @Resource
    BrandService brandService;
    @Resource
    CategoryService categoryService;
    @Resource
    WareFeignClient wareFeignClient;
    @Resource
    SearchFeignClient searchFeignClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoModel> page = this.page(
                new Query<SpuInfoModel>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * //TODO 高级部分完善
     *
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1、保存spu基本信息 pms_spu_info
        SpuInfoModel infoEntity = new SpuInfoModel();
        BeanUtils.copyProperties(vo, infoEntity);
        infoEntity.setCreateTime(LocalDateTime.now());
        infoEntity.setUpdateTime(LocalDateTime.now());
        this.saveBaseSpuInfo(infoEntity);

        //2、保存Spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescModel descEntity = new SpuInfoDescModel();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        imagesService.saveImages(infoEntity.getId(), images);


        //4、保存spu的规格参数;pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueModel> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueModel valueEntity = new ProductAttrValueModel();
            valueEntity.setAttrId(attr.getAttrId());
            AttrModel id = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(id.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());

            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);

        //5、保存spu的积分信息；gulimall_sms->sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        ResultJson r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getStatus() != 200) {
            log.error("远程保存spu积分信息失败");
        }

        //5、保存当前spu对应的所有sku信息；
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoModel skuInfoEntity = new SkuInfoModel();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                //5.1）、sku的基本信息；pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesModel> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesModel skuImagesEntity = new SkuImagesModel();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //返回true就是需要，false就是剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                //5.2）、sku的图片信息；pms_sku_image
                skuImagesService.saveBatch(imagesEntities);
                //TODO 没有图片路径的无需保存

                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueModel> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueModel attrValueEntity = new SkuSaleAttrValueModel();
                    BeanUtils.copyProperties(a, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);

                    return attrValueEntity;
                }).collect(Collectors.toList());
                //5.3）、sku的销售属性信息：pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // //5.4）、sku的优惠、满减等信息；gulimall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                    ResultJson r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getStatus() != 200) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoModel infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoModel> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> w.eq("id", key).or().like("spu_name", key));
        }
        // status=1 and (id=1 or spu_name like xxx)
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }

        /**
         * status: 2
         * key:
         * brandId: 9
         * catelogId: 225
         */

        IPage<SpuInfoModel> page = this.page(
                new Query<SpuInfoModel>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * @description: 商品上架并同步 ES
     * @author: wang pei
     * @date: 2020/5/12 17:05
     **/
    @Override
    public void up(Long spuId) {

        List<SkuInfoModel> skuList = skuInfoService.getSkuListBySpuId(spuId);

        if (CollUtil.isNotEmpty(skuList)) {

            // 获取可检索属性信息
            List<ProductAttrValueModel> baseAttrs = attrValueService.baseAttrlistforspu(spuId);
            List<Long> attrIds = baseAttrs.stream().map(ProductAttrValueModel::getAttrId).collect(Collectors.toList());

            List<AttrModel> attrSearchIds = attrService.list(new LambdaQueryWrapper<AttrModel>()
                    .select(AttrModel::getAttrId)
                    .in(AttrModel::getAttrId, attrIds)
                    .eq(AttrModel::getSearchType, 1));

            Set<Long> searchIdList = attrSearchIds.stream().map(AttrModel::getAttrId).collect(Collectors.toSet());

            // 获取库存
            Map<Long, Boolean> stockMap = null;
            try {
                List<Long> skuIdList = skuList.stream().map(SkuInfoModel::getSkuId).collect(Collectors.toList());
                RUtil<List<SkuHasStockVo>> rUtil = wareFeignClient.hasStock(skuIdList);
                stockMap = rUtil.getData().stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
            } catch (Exception e) {
                e.printStackTrace();
            }

            List<SkuEsModel.Attrs> attrsList = baseAttrs.stream()
                    .filter(item -> searchIdList.contains(item.getAttrId()))
                    .map(item -> {
                        SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                        BeanUtils.copyProperties(item, attrs);

                        return attrs;
                    })
                    .collect(Collectors.toList());

            // 封装 ES 对象信息
            Map<Long, Boolean> finalStockMap = stockMap;
            List<SkuEsModel> skuEsList = skuList.stream().map(sku -> {
                SkuEsModel esModel = new SkuEsModel();

                BeanUtils.copyProperties(sku, esModel);

                esModel.setSkuPrice(sku.getPrice());
                esModel.setSkuImg(sku.getSkuDefaultImg());

                BrandModel brand = brandService.getById(esModel.getBrandId());
                esModel.setBrandName(brand.getName());
                esModel.setBrandImg(brand.getLogo());

                CategoryModel category = categoryService.getById(esModel.getCatalogId());
                esModel.setCatalogName(category.getName());

                // 设置检索属性
                esModel.setAttrs(attrsList);

                esModel.setHotScore(0L);
                // 设置是否有库存
                if (finalStockMap == null) {
                    esModel.setHasStock(true);
                } else {
                    esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
                }

                return esModel;
            }).collect(Collectors.toList());

            // 保存es
            ResultJson resultJson = searchFeignClient.saveProduct(skuEsList);

            log.info(resultJson.toString());
            if (resultJson.getStatus() == 200) {
                baseMapper.updateSpuStatus(spuId, ProductConstant.ProductStatusEnum.SPU_UP.getCode());
            }
        }
    }
}
